<template>
  <div>
    <bread></bread>
    <div class="info">
      <div class="info_up">
        <div class="info_up_title">
          <div><span class="fB">{{detail.title}}</span>（需求编号：{{detail.demandNo}}）</div>
          <div>发布时间：{{detail.createTime}}</div>
        </div>
        <div class="info_up_join">
          <div style="display: flex;">
            <div class="price">预算：
              <span style="color: #469cff;">{{detail.financeBudget}}</span>
            </div>
            <span>需求响应倒计时：</span>
            <a-statistic-countdown :valueStyle="{ color: '#469cff', fontSize: '18px' }" :value="deadline" format="D 天 HH 时 mm 分 ss 秒" />
          </div>
          <a-button type="primary" size="large" @click="response" :disabled="overTime">参与需求</a-button>
        </div>
      </div>
      <div class="info_down">
        <div>需求内容</div>
        <a-row class="row">
          <a-col :span="2" :offset="1">需求类型：</a-col>
          <a-col :span="20">{{dtype[detail.demandType]}}</a-col>
        </a-row>
        <a-row class="row">
          <a-col :span="2" :offset="1">需求描述：</a-col>
          <a-col :span="20" style="word-break: break-all;">{{detail.demandContent}}</a-col>
        </a-row>
        <a-row class="row">
          <a-col :span="2" :offset="1">需求附件：</a-col>
          <a-col :span="20">
            {{detail.demandFileName}}
            <span v-if="detail.demandFileUrl">
              <a-button v-if="canPreview(detail.demandFileUrl)" type="link" @click="toPreview(detail)">预览</a-button>
              <a-button type="link" @click="toDownload(detail)">下载</a-button>
            </span>
          </a-col>
        </a-row>
      </div>
    </div>
  </div>
</template>

<script>
import bread from './components/Bread'
import {queryDemandDetailForMall, response, process} from '@/api/demand'
import storage from '@/utils/storage'
export default {
  components: { bread },
  data () {
    return {
      dtype:{
        '01': '数据产品',
        '02': '数据服务',
        '03': '数据工具',
        '09': '其他',
      },
      overTime: false,
      deadline: Date.now(),
      detail: {}
    }
  },
  created () {
    if (!storage.session.get('authToken') || !storage.session.get('isLogin')) {
      this.$message.error('请登录')
      return this.toGldPath('loginUrl')
    }
    this.loadData()
  },
  methods: {
    async loadData () {
      let res = await queryDemandDetailForMall(this.$route.query)
      let pro = await process(this.$route.query)
      this.detail = res.data || {}
      let { financeType, financeBudget } = this.detail
      let rl = +new Date(this.detail.responseDeadline)
      this.detail.financeBudget = financeType == 2 ? '面议' : ('￥' + (financeBudget || 0).toFixed(2) + '万元')
      this.deadline = rl
      this.overTime = (rl < Date.now()) || (pro.data.length > 0)
    },
    async response(){
      if (!storage.session.get('authToken') || !storage.session.get('isLogin')) {
        return this.$message.error('请登录系统后再参与')
      }
      if(storage.session.get('role') !== 'DATA_PRODUCER'){
        return this.$message.error('当前账号非数据商角色，请切换角色或重新申请角色')
      }
      this.$confirm({
        content:`确认参与[${this.detail.title}]的需求定制服务？`,
        onOk:async ()=>{
          try{
            let res = await response(this.$route.query)
            if(res.code != 0)return
            this.loadData()
            this.$info({title: '需求定制参与成功，请在响应时间结束后参与报价'})
            // this.$confirm({
            //   content: '需求定制参与成功，是否前往立即报价？',
            //   okText: '立即报价',
            //   cancelText: '稍后报价',
            //   onOk:()=>{
            //     location.href = location.origin + location.pathname + 'manage/#/demand/detail?id=' + this.detail.id
            //   }
            // })
          }catch(e){
            //TODO handle the exception
          }
        }
      })
    },
    canPreview(fileUrl){
      return fileUrl.endsWith('.png') || fileUrl.endsWith('.jpg') || fileUrl.endsWith('.jpeg') || fileUrl.endsWith('.gif') || fileUrl.endsWith('.ico') || fileUrl.endsWith('.svg');
    },
    toPreview(file) {
      if (file.demandFileUrl) {
        if (canPreview(file.demandFileUrl)) {
          // 可以在线预览
          window.open(file.demandFileUrl)
        } else {
          this.toDownload(file)
        }
      } else {
        this.$message.error('文件地址路径不完整')
      }
    },
    toDownload(file) {

      if (file.storageFileId) {
        let url = appConfig.microServ + appConfig.microServModules.file + "api/fdfs/file/download?storage_file_id=" + file.storageFileId
        this.getBlob(url,file.demandFileName)
      } else {
        if (file.demandFileUrl) {
          this.getBlob(file.demandFileUrl,file.demandFileName)
        } else {
          this.$message.error('文件地址路径不完整')
        }
      }

      // if (file.demandFileId) {
      //   window.open(
      //     appConfig.microServ +
      //     appConfig.microServModules.file +
      //     "api/fdfs/file/download?storage_file_id=" +
      //     file.demandFileId
      //   );
      // } else {
        // if (file.demandFileUrl) {
        //   window.open(file.demandFileUrl)
        // } else {
        //   this.$message.error('文件地址路径不完整')
        // }
      // }
    },
    /**
     * 重命名下载
     * @param  {String} url 目标文件地址
     */
    getBlob(url,filename) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) this.saveAs(xhr.response, filename);
      };
      xhr.onerror = () =>this.$message.error('下载地址路径错误')
      xhr.send();
    },
    /**
     * 保存
     * @param  {Blob} blob
     * @param  {String} filename 想要保存的文件名称
     */
    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, filename);
      } else {
        var link = document.createElement('a');
        var body = document.querySelector('body');
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        link.style.display = 'none';
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      };
    }
  }
}
</script>

<style scoped lang="scss">
$width: 1200px;
$mainColor: #0078FE;
.flex_b{
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info {
  width: $width;
  margin: 20px auto;
  font-size: 18px;
  &_up{
    padding: 30px 20px;
    border-bottom: 1px solid #ccc;
    &_title{
      @extend .flex_b ;
      margin-bottom: 20px;
      .fB{
        font-size: 20px;
        font-weight: 700;
      }
    }
    &_join{
      @extend .flex_b ;
      .price{
        display: inline-block;
        min-width: 166px;
        margin-right: 30px;
      }
    }
  }
  &_down{
    padding: 20px;
  }
}
.row{
  margin: 30px 0;
}

</style>
